const MiddlewareEventEmitter = require('../utils/MiddlewareEventEmitter');
global.utils = require('../utils/util.js');
require('./config.js');
global.CONSTANTS = require('./constants.js');

global.PAPI = null;
global.GMLIB_MC = null;
global.GMLIB_SC = null;

const WebsocketClient = require("../ws_frame/client/client.js");
const { Client } = require('./class/Client.js');

// 新建WSC连接对象
global.WSC = new WebsocketClient(
    {
        name: CONF.CONFIG.get('Websocket')['ServerName'],
        connectUrl: CONF.CONFIG.get('Websocket')['ConnectUrl'],
        connectKey: CONF.CONFIG.get('Websocket')['ConnectKey'],
        reconnectInterval: 5000,
        Client: Client
    }
);

// 设置日志
WSC.logger.name = 'WS协调客户端';
if (CONF.CONFIG.get('Websocket')['Debug'] == true){
    WSC.logger.setConsole(true, 5);
    WSC.logger.debug(`### WS协调客户端Debug模式开启 ###`);
}

// 输出版本
WSC.on('open', ()=>{
    WSC.logger.info('WS协调客户端版本: ' + VERSION.join('.'));
});

// 初始化回环监听器
WSC.api = {
    listener: new MiddlewareEventEmitter(),
    remoteCallFunctions: {} // 导入的其他插件的监听函数
};
WSC.addApiEventName = function addApiEventName(eventName){
    this.api.remoteCallFunctions[eventName] = {};
    return true;
};

try{
    PAPI = require("../../../GMLIB-LegacyRemoteCallApi/lib/BEPlaceholderAPI-JS").PAPI;
    GMLIB_MC = require("../../../GMLIB-LegacyRemoteCallApi/lib/GMLIB_API-JS").Minecraft;
    GMLIB_SC = require("../../../GMLIB-LegacyRemoteCallApi/lib/GMLIB_API-JS").Scoreboard;
}catch(e){
    WSC.logger.error(e);
    WSC.logger.error('需要前置插件: GMLIB-LegacyRemoteCallApi');
}

// 路由模块
require('./router/router.js');

// llapi模块, 监听路由功能中的事件
const {registerPAPI} = require('./llapi.js');

// 注册PAPI
registerPAPI();

ll?.onUnload(()=>{
    WSC.close();
});

mc.listen("onServerStarted", ()=>{
    // 注册cmd
    require('./cmd.js');
    // 开启WSC连接
    WSC.connect();
    setTimeout(()=>{},1); 
});


